<template>
  <table>
    <thead>
      <th>商品图片</th>
      <th>商品标题</th>
      <th>状态</th>
      <th>操作</th>
    </thead>
    <tr v-for="(item, index) in list" :key="item.id">
      <td>
        <img :src="item.productImage" alt="加载图片" />
      </td>
      <td>{{ item.productName }}</td>
      <td>{{ changeState[index] }}</td>
      <td>
        <p v-show="item.productStatus === 0" @click="keyMade(item.id)">
          一键生成
        </p>
        <p v-show="item.productStatus === 2" @click="del(item.id)">删除</p>
      </td>
    </tr>
  </table>
</template>
<script setup>
import axios from "axios";
import { onMounted, ref, watch } from "vue";

const list = ref([]); //存储所有数据
const changeState = ref([]); //存储数据状态
/**
 * 获取所有请求
 */
const getAllList = async () => {
  const result = await axios.get("http://localhost:3000/products");
  list.value = result.data;
  console.log(list.value);
};

/**
 * 一键生成
 */
const keyMade = async (id) => {
  const result = await axios.patch(`http://localhost:3000/products/${id}`, {
    productStatus: 1,
  });
  list.value[id - 1].productStatus = result.data.productStatus;
  console.log(list.value[id - 1]);
};

/**
 * 删除
 */
const del = async (id) => {
  const result = await axios.patch(`http://localhost:3000/products/${id}`, {
    productStatus: 0,
  });
  list.value[id - 1].productStatus = result.data.productStatus;
  console.log(list.value[id - 1]);
};
onMounted(() => {
  getAllList();
});
watch(
  list,
  (newValue) => {
    changeState.value = newValue.map((item) => {
      if (item.productStatus === 0) {
        return "未生成";
      }
      if (item.productStatus === 1) {
        return "处理中";
      }
      if (item.productStatus === 2) {
        return "已生成";
      }
    });
  },
  {
    deep: true,
    immediate: true,
  }
);
</script>
<style lang="scss">
table {
  width: 600px;
  margin: 0 auto;
  th {
    width: 200px;
  }
  td {
    text-align: center;
    img {
      width: 200px;
      vertical-align: top;
    }
    p {
      color: skyblue;
    }
  }
}
</style>
